<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">

          <!--          <a-col :xl="6" :lg="7" :md="8" :sm="24">
                      <a-form-item label="商品ID">
                        <j-popup placeholder="请选择商品ID" v-model="queryParam.goodsId" code="SelectorGoods" org-fields="id" dest-fields="goods_id" :field="getPopupField('goods_id')" :multi="true"/>
                      </a-form-item>
                    </a-col>-->
          <a-col :xl="10" :lg="11" :md="12" :sm="24">
            <a-form-item label="制单日期">
              <j-date placeholder="请选择开始日期" class="query-group-cust" v-model="queryParam.createTime_begin"></j-date>
              <span class="query-group-split-cust"></span>
              <j-date placeholder="请选择结束日期" class="query-group-cust" v-model="queryParam.createTime_end"></j-date>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>

              <!--              <a @click="handleToggleSearch" style="margin-left: 8px">
                              {{ toggleSearchStatus ? '收起' : '展开' }}
                              <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
                            </a>-->
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button v-if="activeKey=='approved'"type="primary" icon="download" @click="handleExportXls('发货商品赤字管理')">导出</a-button>
      <a-button v-if="activeKey=='approved'"@click="openButton('1')" type="primary" icon="check">开启</a-button>
      <a-button v-if="activeKey=='approved'"@click="openButton('0')" type="danger" ghost icon="close">关闭</a-button>
      <!--    <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
           <a-button type="primary" icon="import">导入</a-button>
         </a-upload>
         &lt;!&ndash; 高级查询区域 &ndash;&gt;
         <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>
         <a-dropdown v-if="selectedRowKeys.length > 0">
           <a-menu slot="overlay">
             <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
           </a-menu>
           <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
         </a-dropdown>-->
    </div>

    <!-- table区域-begin -->

    <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
            <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
            <a style="margin-left: 24px" @click="onClearSelected">清空</a>

      <span style="float:right;">
          <a-popover title="自定义列" trigger="click" placement="leftBottom">
            <template slot="content">
              <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
                <a-row style="width: 400px">
                  <template v-for="(item,index) in defColumns">
                    <template v-if="item.key!=='rowIndex'&& item.dataIndex!=='action'">
                        <a-col :span="12"><a-checkbox :value="item.dataIndex"><j-ellipsis :value="item.title" :length="10"></j-ellipsis></a-checkbox></a-col>
                    </template>
                  </template>
                </a-row>
              </a-checkbox-group>
            </template>
            <a><a-icon type="setting" />设置</a >
          </a-popover>
        </span>
    </div>
    <a-tabs v-model="activeKey" @change="handleChangeTab">
      <a-tab-pane key="notGenerated" tab="暂存中">
      <div>
        <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="dateilId"
          class="j-table-force-nowrap1"
          :scroll="{x:true}"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          :rowSelection="{type:'radio',selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
          @change="handleTableChange">

          <template slot="htmlSlot" slot-scope="text">
            <div v-html="text"></div>
          </template>
          <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>

          <a-divider type="vertical" />
           <act-apply-btn
                 @success="handleChangeTab"
                  :data-id="record.id"
                  :serviceName="serviceName"
                 :variables="record"
              ></act-apply-btn>
          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

        </a-table>
      </div>
      </a-tab-pane>
      <a-tab-pane key="needEdit" tab="需修改">
        <div>
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="detailId"
            class="j-table-force-nowrap1"
            :scroll="{x:true}"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            :rowSelection="{type:'radio',selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
            @change="handleTableChange">

            <template slot="htmlSlot" slot-scope="text">
              <div v-html="text"></div>
            </template>

            <span slot="action" slot-scope="text, record">
          <a v-if="record.status < 0" @click="handleEdit(record)">编辑</a>

             <a-divider v-if="record.status < 0"  type="vertical" />
                <act-apply-btn
                  v-show="record.actStatus == '撤回'"
                  @success="handleChangeTab"
                  :data-id="record.id"
                  :serviceName="serviceName"
                  :variables="record"
                ></act-apply-btn>
              <a-popconfirm  v-if="record.actStatus != '撤回'" title="确定取消申请吗?" @confirm="() => handleStop(record)">
               <a href="javascript:;">取消申请</a>
              </a-popconfirm>
              <a-divider v-if="record.actStatus != '撤回'" type="vertical" />
              <act-historic-detail-btn :data-id="record.id"></act-historic-detail-btn>
             <a-divider type="vertical" />
               <a @click="handleDetail(record)">详情</a>
        </span>

          </a-table>
        </div>
      </a-tab-pane>

      <a-tab-pane key="approving" tab="审核中">
        <div>
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="detailId"
            class="j-table-force-nowrap1"
            :scroll="{x:true}"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            :rowSelection="{type:'radio',selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
            @change="handleTableChange">

            <template slot="htmlSlot" slot-scope="text">
              <div v-html="text"></div>
            </template>

            <span slot="action" slot-scope="text, record">
          <act-historic-detail-btn :data-id="record.id"></act-historic-detail-btn>
          <a-divider type="vertical" />
         <a @click="handleDetail(record)">详情</a>
           <a-divider v-if="record.actStatus != '撤回'" type="vertical" />
              <a-popconfirm  v-if="record.actStatus != '撤回'" title="确定取消申请吗?" @confirm="() => handleStop(record)">
               <a href="javascript:;">取消申请</a>
              </a-popconfirm>
        </span>

          </a-table>
        </div>
      </a-tab-pane>

      <a-tab-pane key="approved" tab="已审批">
        <div>
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="detailId"
            class="j-table-force-nowrap1"
            :scroll="{x:true}"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            :rowSelection="{type:'radio',selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
            @change="handleTableChange">

            <template slot="htmlSlot" slot-scope="text">
              <div v-html="text"></div>
            </template>

            <span slot="action" slot-scope="text, record">
            <act-historic-detail-btn :data-id="record.id"></act-historic-detail-btn>
          <a-divider type="vertical" />
          <a @click="handleDetail(record)">详情</a>
        </span>

          </a-table>
        </div>
      </a-tab-pane>

    </a-tabs>
      <crm-deficit-management-modal ref="modalForm" @ok="modalFormOk"/>
  </a-card>
</template>

<script>

import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import CrmDeficitManagementModal from './modules/CrmDeficitManagementModal'
import {filterMultiDictText} from '@/components/dict/JDictSelectUtil'
import '@/assets/less/TableExpand.less'
import ActApplyBtn from "@views/flowable/components/ActApplyBtn";
import ActCancelBtn from "@views/flowable/components/ActCancelBtn";
import ActHandleBtn from "@views/flowable/components/ActHandleBtn";
import ActHistoricDetailBtn from "@views/flowable/components/ActHistoricDetailBtn";
import {getAction, postAction} from "@api/manage";
import {filterObj} from "@/utils/util";
import {stopProcess} from "@views/flowable/api/process";

export default {
  name: "CrmDeficitManagementList",
  mixins:[JeecgListMixin],
  components: {
    CrmDeficitManagementModal,
    ActApplyBtn,
    ActCancelBtn,
    ActHandleBtn,
    ActHistoricDetailBtn,
  },
  data () {
    return {
      description: '发货商品赤字管理管理页面',
      activeKey:'notGenerated',
      serviceName:'deficitManagementService',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key:'rowIndex',
          width:60,
          align:"center",
          customRender:function (t,r,index) {
            return parseInt(index)+1;
          }
        },
        {
          title:'发货赤字单号',
          align:"center",
          dataIndex: 'deficitCode'
        },
        {
          title:'发货类型',
          align:"center",
          dataIndex: 'shipmentType'
        },
        {
          title:'物料编码',
          align:"center",
          dataIndex: 'packageCode'
        },
        {
          title:'物料名称',
          align:"center",
          dataIndex: 'packageName'
        },
        {
          title:'规格型号',
          align:"center",
          dataIndex: 'noneSpec'
        },
        {
          title:'主计量单位',
          align:"center",
          dataIndex: 'meUnit_dictText'
        },
        {
          title:'主计量数量',
          align:"center",
          dataIndex: 'mainQuantity'
        },
        {
          title:'辅计量单位',
          align:"center",
          dataIndex: 'auUnit_dictText'
        },
        {
          title:'辅计量数量',
          align:"center",
          dataIndex: 'auxiliaryQuantity'
        },
        {
          title:'单价',
          align:"center",
          dataIndex: 'unitPrice'
        },
        {
          title:'金额',
          align:"center",
          dataIndex: 'amountMoney'
        },
        {
          title:'仓库实收数量',
          align:"center",
          dataIndex: 'receivedQuantity'
        },
        {
          title:'不合格数量',
          align:"center",
          dataIndex: 'unqualifiedQuantity'
        },
        {
          title:'合格数量',
          align:"center",
          dataIndex: 'qualifiedQuantity'
        },

        {
          title:'制单人',
          align:"center",
          dataIndex: 'createBy_dictText'
        },
        {
          title:'制单部门',
          align:"center",
          dataIndex: 'sysOrgCode_dictText'
        },
        {
          title:'制单日期',
          align:"center",
          dataIndex: 'createTime'
        },

        {
          title:'是否打印',
          align:"center",
          dataIndex: 'isPrint_dictText'
        },
        {
          title:'是否开启',
          align:"center",
          dataIndex: 'isOpen_dictText'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align:"center",
          fixed:"right",
          width:147,
          scopedSlots: { customRender: 'action' },
        }
      ],
      settingColumns: [],
      defColumns: [
        {
          title: '#',
          dataIndex: '',
          key:'rowIndex',
          width:60,
          align:"center",
          customRender:function (t,r,index) {
            return parseInt(index)+1;
          }
        },
        {
          title:'发货赤字单号',
          align:"center",
          dataIndex: 'deficitCode'
        },
        {
          title:'发货类型',
          align:"center",
          dataIndex: 'shipmentType'
        },
        {
          title:'物料编码',
          align:"center",
          dataIndex: 'packageCode'
        },
        {
          title:'物料名称',
          align:"center",
          dataIndex: 'packageName'
        },
        {
          title:'规格型号',
          align:"center",
          dataIndex: 'noneSpec'
        },
        {
          title:'主计量单位',
          align:"center",
          dataIndex: 'meUnit_dictText'
        },
        {
          title:'主计量数量',
          align:"center",
          dataIndex: 'mainQuantity'
        },
        {
          title:'辅计量单位',
          align:"center",
          dataIndex: 'auUnit_dictText'
        },
        {
          title:'辅计量数量',
          align:"center",
          dataIndex: 'auxiliaryQuantity'
        },
        {
          title:'单价',
          align:"center",
          dataIndex: 'unitPrice'
        },
        {
          title:'金额',
          align:"center",
          dataIndex: 'amountMoney'
        },
        {
          title:'仓库实收数量',
          align:"center",
          dataIndex: 'receivedQuantity'
        },
        {
          title:'不合格数量',
          align:"center",
          dataIndex: 'unqualifiedQuantity'
        },
        {
          title:'合格数量',
          align:"center",
          dataIndex: 'qualifiedQuantity'
        },

        {
          title:'制单人',
          align:"center",
          dataIndex: 'createBy_dictText'
        },
        {
          title:'制单部门',
          align:"center",
          dataIndex: 'sysOrgCode_dictText'
        },
        {
          title:'制单日期',
          align:"center",
          dataIndex: 'createTime'
        },

        {
          title:'是否打印',
          align:"center",
          dataIndex: 'isPrint_dictText'
        },
        {
          title:'是否开启',
          align:"center",
          dataIndex: 'isOpen_dictText'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align:"center",
          fixed:"right",
          width:147,
          scopedSlots: { customRender: 'action' },
        }
      ],
      url: {
        list: "/deficit/crmDeficitManagement/list",
        delete: "/deficit/crmDeficitManagement/delete",
        deleteBatch: "/deficit/crmDeficitManagement/deleteBatch",
        exportXlsUrl: "/deficit/crmDeficitManagement/exportXls",
        importExcelUrl: "deficit/crmDeficitManagement/importExcel",
        editIsOpen: "deficit/crmDeficitManagement/editIsOpen",
      },
      dictOptions:{},
      superFieldList:[],
    }
  },
  created() {
    this.getSuperFieldList();
  },
  computed: {
    importExcelUrl: function(){
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    }
  },
  methods: {
    openButton(code){
      if (this.selectionRows.length == 0) {
        this.$message.warn('请选择一条记录！')
        return
      }
      const rows = this.selectionRows[0]

      getAction(this.url.editIsOpen, {id:rows.id,isOpen:code}).then((res)=>{
        if(res.code==200){
          this.$message.success(res.message);
          // that.$emit('ok');
        }else{
          this.$message.warning(res.message);
        }
      }).finally(() => {
        this.handleChangeTab()
      })

    },
    handleStop(row) {
      const params = {
        instanceId: row.processInstanceId,
      }
      stopProcess(params).then((res) => {
        this.$message.success(res.message)
        this.handleChangeTab()
      })
    },
    searchQuery() {
      if(typeof this.beforeSearch === 'function'){
        let isreturn = this.beforeSearch()
        if(!isreturn){
          return;
        }
      }
      switch (this.activeKey) {
        case 'notGenerated':
          this.loadData(1,-2)
          break
        case 'needEdit':
          this.loadData(1,-1)
          break
        case 'approving':
          this.loadData(1,0)
          break
        case 'approved':
          this.loadData(1,999)
          break
        default:
          break
      }
      // 点击查询清空列表选中行
      // https://gitee.com/jeecg/jeecg-boot/issues/I4KTU1
    },
    searchReset(noClearQueryParam) {
      if (noClearQueryParam === false) {
        //不清参数
      } else {
        this.queryParam = {};
      }
      switch (this.activeKey) {
        case 'notGenerated':
          this.loadData(1,-2)
          break
        case 'needEdit':
          this.loadData(1,-1)
          break
        case 'approving':
          this.loadData(1,0)
          break
        case 'approved':
          this.loadData(1,999)
          break
        default:
          break
      }
    },

    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      console.log(pagination)
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field;
        this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
      }
      this.ipagination = pagination;
      switch (this.activeKey) {
        case 'notGenerated':
          this.loadData(0,-2)
          break
        case 'needEdit':
          this.loadData(0,-1)
          break
        case 'approving':
          this.loadData(0,0)
          break
        case 'approved':
          this.loadData(0,999)
          break
        default:
          break
      }
    },
    getQueryParams() {
      //获取查询条件
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters);
      // param.field = this.getQueryField();
      param.pageNo = this.ipagination.current;
      param.pageSize = this.ipagination.pageSize;
      return filterObj(param);
    },
    modalFormOk() {
      // 新增/修改 成功时，重载列表
      switch (this.activeKey) {
        case 'cg':
          this.loadData(0,999)
          break
        case 'notGenerated':
          this.loadData(0,-2)
          break
        case 'needEdit':
          this.loadData(0,-1)
          break
        case 'approving':
          this.loadData(0,0)
          break
        case 'approved':
          this.loadData(0,999)
          break
        default:
          break
      }
      //清空列表选中
      this.onClearSelected()
    },
    loadData(arg,status) {
      if (!this.url.list) {
        this.$message.error("请设置url.list属性!")
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      var params = this.getQueryParams();//查询条件
      if(status==null){
        params.status = -2
      }else{
        params.status = status
      }
      this.loading = true;
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          this.dataSource = res.result.records || res.result;
          this.dataSourceBack=this.dataSource
          if (res.result.total) {
            this.ipagination.total = res.result.total;
          } else {
            this.ipagination.total = 0;
          }
          //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.loading = false
      })

    },
    handleChangeTab() {
      switch (this.activeKey) {
        case 'notGenerated':
          this.loadData(1,-2)
          break
        case 'needEdit':
          this.loadData(1,-1)
          break
        case 'approving':
          this.loadData(1,0)
          break
        case 'approved':
          this.loadData(1,999)
          break
        default:
          break
      }
    },
    initDictConfig(){
    },
    getSuperFieldList(){
      let fieldList=[];
      fieldList.push({type:'string',value:'createBy',text:'制单人',dictCode:"sys_user,realname,username"})
      fieldList.push({type:'datetime',value:'createTime',text:'制单日期'})
      fieldList.push({type:'string',value:'sysOrgCode',text:'制单部门',dictCode:"sys_depart,depart_name,org_code"})
      fieldList.push({type:'string',value:'deficitCode',text:'发货赤字单号',dictCode:''})
      fieldList.push({type:'string',value:'flowFlag',text:'审批流程',dictCode:'deficit_flow_type'})
      fieldList.push({type:'string',value:'customerName',text:'客户名称',dictCode:'deficit_customer'})
      fieldList.push({type:'sel_user',value:'salesman',text:'业务员'})
      fieldList.push({type:'string',value:'priceType',text:'单价类型',dictCode:'unit_price_type'})
      fieldList.push({type:'string',value:'moneyUnit',text:'币种',dictCode:'money_unit'})
      fieldList.push({type:'Text',value:'reason',text:'退货原因',dictCode:''})
      fieldList.push({type:'string',value:'shipmentType',text:'发货类型',dictCode:''})
      fieldList.push({type:'string',value:'isPrint',text:'是否打印',dictCode:'yn'})
      fieldList.push({type:'string',value:'isOpen',text:'是否开启',dictCode:'yn'})
      this.superFieldList = fieldList
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>